package com.jar.exercise.集合和数据结构.手写hashmap;

import java.util.LinkedList;
import java.util.Map;

/**
 * @author ZhangShengHao
 * @className MyArrayListMap
 * @description TODO
 * @date 2019/12/30 22:45
 */
public class MyLinkListMap<K, V> implements MyMap<K, V> {
	LinkedList<Node>[] object = new LinkedList[100];
	private int size;

	@Override
	public int size() {
		return size;
	}

	@Override
	public V get(K k) {
		int index = k.hashCode() % object.length;
		LinkedList<Node> nodes = object[index];
		for (Node node : nodes) {
			if (node.getKey().equals(k)) {
				return node.getValue();
			}
		}
		return null;
	}

	@Override
	public V put(K k, V v) {
		int index = k.hashCode() % object.length;
		LinkedList<Node> nodes = object[index];
		if (nodes == null) {//就是hashcode没有碰撞
			nodes = new LinkedList<>();//创建一个链表
			//说明已经产生了冲突
			nodes.add(new Node(k, v));
			object[index] = nodes;
			return v;
		}
		for (Node node : nodes) {
			if (node.getKey().equals(k)) {
				node.setValue(v);
				return v;
			}
		}
		return null;
	}

	class Node implements Map.Entry<K, V> {
		private V v;
		private K k;

		public Node(K k, V v) {
			this.v = v;
			this.k = k;
		}

		@Override
		public K getKey() {
			return k;
		}

		@Override
		public V getValue() {
			return v;
		}

		@Override
		public V setValue(V value) {
			V oldValue = v;
			v = value;
			return oldValue;
		}
	}
}
